<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;
use App\Models\Topic;
use App\Models\Message;
use App\Models\User;
use Auth;
use App\Models\SubtopicModerator;
use App\Models\SubtopicSubscriber;

use App\Http\Requests\NewPostRequest;

class PostController extends Controller
{
	public function showPost(string $sub,string $post_id){
		$post = Post::where('subwroteit','=',$sub)->where('post_id_string','=',$post_id)->first();
        return view('wroteit.show_post')->with(['post' => $post]);
	}
	public function subscribe(string $sub){
		$userid=Auth::user()->id;
        $rel = array('subtopic' => $sub, 'subscriber_id' => $userid);
        SubtopicSubscriber::create($rel);
        return redirect()->route('show_topic',['sub' => $sub]);
	}

	public function showTopics(){
		$topics = Topic::orderby('updated_at','desc')->get();
        return view('wroteit.list_topics')->with(['topics' => $topics]);
	}
	public function showSubscriptions(){
		$subbed = SubtopicSubscriber::select('subtopic')->where('subscriber_id',Auth::user()->id);
    	$topics = Topic::orderby('updated_at','desc')->whereIn('title',$subbed)->paginate(6);
        return view('wroteit.list_topics')->with(['topics' => $topics]);
	}
	public function newPost(string $sub){
		return view('wroteit.new_post')->with(['sub' => $sub]);
	}
    public function storeNewPost(NewPostRequest $request){
		$post = new Post;
		$post->title = $request->input('title');
		$post->content = $request->input('content');
        $post->by_user = Auth::user()->name;
		$post->subwroteit = $request->input('sub');
		$post->post_id_string = "kel";
		$post->score = 0;
		$post->number_comments = 0;
		$post->save();
        //$this->store_relation_subtopicSubscriber($subtopic_name, $user_id);
        return redirect()->route('show_post')->with(['sub' => $request->input('sub')])->with(['post_id' => $post->post_id_string]);
    }

}
